import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export interface AppSettings {
  theme: 'light' | 'dark';
  navbar: boolean;
  menu: boolean;
  topMenu: boolean;
  hideMenu: boolean;
  footer: boolean;
  tabBar: boolean;
  menuCollapse: boolean;
  menuWidth: number;
  device: 'desktop' | 'mobile';
}

const defaultSettings: AppSettings = {
  theme: 'light',
  navbar: true,
  menu: true,
  topMenu: false,
  hideMenu: false,
  footer: true,
  tabBar: true,
  menuCollapse: false,
  menuWidth: 220,
  device: 'desktop'
};

export const useAppStore = defineStore(
  'app',
  () => {
    const settings = ref<AppSettings>({ ...defaultSettings });

    // Getters
    const theme = computed(() => settings.value.theme);
    const navbar = computed(() => settings.value.navbar);
    const menu = computed(() => settings.value.menu);
    const topMenu = computed(() => settings.value.topMenu);
    const hideMenu = computed(() => settings.value.hideMenu);
    const footer = computed(() => settings.value.footer);
    const tabBar = computed(() => settings.value.tabBar);
    const menuCollapse = computed(() => settings.value.menuCollapse);
    const menuWidth = computed(() => settings.value.menuWidth);
    const device = computed(() => settings.value.device);

    // Actions
    const updateSettings = (newSettings: Partial<AppSettings>) => {
      settings.value = { ...settings.value, ...newSettings };
    };

    const resetSettings = () => {
      settings.value = { ...defaultSettings };
    };

    const toggleTheme = () => {
      settings.value.theme = settings.value.theme === 'light' ? 'dark' : 'light';
    };

    const toggleMenuCollapse = () => {
      settings.value.menuCollapse = !settings.value.menuCollapse;
    };

    const setDevice = (deviceType: 'desktop' | 'mobile') => {
      settings.value.device = deviceType;

      // 移动端自动调整设置
      if (deviceType === 'mobile') {
        settings.value.hideMenu = true;
        settings.value.tabBar = false;
      } else {
        settings.value.hideMenu = false;
        settings.value.tabBar = true;
      }
    };

    return {
      // State
      settings,

      // Getters
      theme,
      navbar,
      menu,
      topMenu,
      hideMenu,
      footer,
      tabBar,
      menuCollapse,
      menuWidth,
      device,

      // Actions
      updateSettings,
      resetSettings,
      toggleTheme,
      toggleMenuCollapse,
      setDevice
    };
  },
  {
    persist: {
      key: 'app-settings',
      storage: localStorage,
      pick: ['settings']
    }
  }
);
